#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MAX_BUFFER_SIZE 1024

int main(int argc, char *argv[]) {
    int server_fd, new_socket, valread;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[MAX_BUFFER_SIZE] = {0};
    char *message = "Hello from Server";

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("Socket creation failed");
        return -1;
    }

    // 设置套接字选项，允许端口重用
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("Setsockopt failed");
        return -1;
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(8080);

    // 绑定套接字到地址
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("Bind failed");
        return -1;
    }

    // 开始监听，最大连接数为5
    if (listen(server_fd, 5) < 0) {
        perror("Listen failed");
        return -1;
    }
    struct sockaddr_in  cliaddr;
    while(1) {
        printf("Waiting for connection...\n");

        // 接受客户端连接请求
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
            perror("Accept failed");
            return -1;
        }
        
        printf("Connection accepted\n");

        // 读取客户端发来的数据
        socklen_t len = sizeof(address);
        memset(&cliaddr, 0, sizeof(cliaddr));
        int n = recvfrom(new_socket, (char *)buffer, MAX_BUFFER_SIZE, 0, (struct sockaddr *)&cliaddr, &len);
        printf("Client: %s\n", buffer );

        // 发送消息给客户端
        sendto(new_socket, message, strlen(message), 0, (const struct sockaddr *)&cliaddr, len);
        printf("Hello message sent\n");

        close(new_socket); // 关闭已连接的套接字
    }

    return 0;
}